package com.jian.springbootdemosdk;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jian.project.model.dto.dbinterface.DbInterfaceApiRequest;
import com.jian.springbootdemosdk.utils.Invoke;
import com.jian.springbootdemosdk.utils.JApiUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class JApiClient {
    private String accessKey;
    private String securityKey;
    public static final Map<String, Invoke> invoke = new ConcurrentHashMap<>();

    public JApiClient(String accessKey, String securityKey) {
        this.accessKey = accessKey;
        this.securityKey = securityKey;
    }

    public String getName(String name, Long interfaceId) {
        String url = "localhost:8111/api/demo/json";
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("name", name);
        HttpRequest request = HttpRequest.post(url)
                .contentType("application/json;charset=utf-8")
                .body(jsonObject.toString())

                .addHeaders(JApiUtils.getHead(name, interfaceId, accessKey, securityKey));
        HttpResponse response = request.execute();
        System.out.println(response);
        return response.body();
    }

    public String getName(DbInterfaceApiRequest dbInterfaceApiRequest) {
        String param = dbInterfaceApiRequest.getDbInterfaceInfo().getRequestParam();
        Object name = JSONUtil.parseObj(param).get("name");
        String url = "localhost:8111/api/demo/json";

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("name", name);
        HttpRequest request = HttpRequest.post(url)
                .contentType("application/json;charset=utf-8")
                .body(jsonObject.toString())
                .addHeaders(JApiUtils.getHead(name,
                        dbInterfaceApiRequest.getDbInterfaceInfo().getId(), accessKey, securityKey));
        HttpResponse response = request.execute();
        return response.body();
    }

    public String getTime(DbInterfaceApiRequest dbInterfaceApiRequest) {
        String url = dbInterfaceApiRequest.getDbInterfaceInfo().getUrl();
        HttpRequest request = HttpRequest.get(url)
                .contentType("application/json;charset=utf-8")
                .addHeaders(JApiUtils.getHead(System.currentTimeMillis(),
                        dbInterfaceApiRequest.getDbInterfaceInfo().getId(), accessKey, securityKey));
        HttpResponse response = request.execute();
        return response.body();
    }

    public Object invokeApi(DbInterfaceApiRequest dbInterfaceApiRequest) {
        Invoke invoke = JApiClient.invoke.get(dbInterfaceApiRequest.getDbInterfaceInfo().getUrl());
        if (invoke == null)
            return null;
        return invoke.invoke(dbInterfaceApiRequest);
    }
}
